package com.springboot.demo.linked;


/**
 * 单向链表
 *
 * @author supu
 * @create 2018-06-04 10:41
 **/
public class LinkedList {
    /**
     * 头结点
     */
    private Node head;
    /**
     * 节点长度
     */
    private int count;

    public LinkedList() {
        //构造函数用来初始化
        this.head = null;
        count = 0;
    }

    // 添加节点
    public void addNode(Node node) {
        Node temp = null;
        if (head != null) {
            temp = head;
            while (temp.getNext() != null) {
                temp = temp.getNext();
            }
            temp.setNext(node);
        } else {
            head = node;
        }
        count++;
    }

    // 删除节点
    public void removeNode(Node node) {
        Node temp = head;
        Node front = null;
        while (temp != null) {
            if (node.getData() == temp.getData()) {
                break;
            }
            front = temp;
            temp = temp.getNext();
        }
        if (temp != null) {
            if (front != null) {
                if (temp.getNext() == null) {
                    front.setNext(null);
                } else {
                    front.setNext(temp.getNext());
                }
            } else {
                head = head.getNext();
            }
            count--;
        }
    }

    // 更新节点
    public <T> void updateNode(Node node, T data) {
        Node temp = head;
        while (temp != null) {
            if (node.getData() == temp.getData()) {
                temp.setData(data);
                break;
            }
            temp = temp.getNext();
        }
    }

    // 打印节点信息
    public void printNode() {
        Node temp = head;
        StringBuilder stringBuilder = new StringBuilder();
        while (temp != null) {
            stringBuilder.append(temp.getData()).append(",");
            temp = temp.getNext();
        }
        System.out.println("链表总结点数：" + count + ", 链表数据：" + stringBuilder.toString());
        System.out.println("*************************************");
    }
}
